package com.playball.lottery.frm.buyhall;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.MyDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.help.CaiPiaoHelp;
import com.playball.lottery.frm.kjinfo.KjinfoListByType;
import com.playball.lottery.frm.yhzx.BetProtocolActivity;
import com.playball.lottery.frm.yhzx.BetRecordActivity;
import com.playball.lottery.frm.yhzx.JddRechargeListActivity;
import com.playball.lottery.frm.yhzx.LoginActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.FactoryNum;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.MyPreference;


/**
 * 传统足球 - 任选9
 * 
 * @author tanglizhong
 * @version 2014-4-1 下午3:54:52
 */
public class CtzqRx9Activity extends BaseActivity {

	/** 顶部标题栏左侧 */
	TextView buy_ctzq_top_tv_left;
	/** 顶部标题栏右侧 */
	TextView buy_ctzq_top_tv_right;
	/** 顶部标题栏中间内容 */
	TextView buy_ctzq_top_tv_title;

	/** 比赛信息布局 */
	View view_buy_ctzq_rx9_matches;
	/** 期数及截止时间 */
	TextView buy_ctzq_rx9_issue_and_endtime;
	/** 比赛列表 */
	ListView buy_ctzq_rx9_list;
	/** 底部菜单栏左侧 */
	Button buy_ctzq_bottom_tv_left;
	/** 底部菜单栏右侧 */
	TextView buy_ctzq_bottom_tv_right;
	/** 底部菜单栏中间提示 */
	TextView buy_ctzq_bottom_tv_title;

	/** 投注布局 */
	View view_buy_ctzq_rx9_bet;
	/** 投注情况和截止日期 */
	TextView buy_ctzq_rx9_matches_and_endtime;
	/** 添加比赛按钮 */
	View buy_ctzq_rx9_add_match;
	/** 清空选项按钮 */
	View buy_ctzq_rx9_clear_match;
	/** 投注列表 */
	ListView buy_ctzq_rx9_list_bet;
	/** 投注倍数 */
	EditText buy_ctzq_bottom_et_a_multiple;
	/** 底部菜单栏左侧 */
	TextView buy_ctzq_bottom_tv_left_bet;
	/** 底部菜单栏右侧 */
	TextView buy_ctzq_bottom_tv_right_bet;
	/** 底部菜单栏中间提示 */
	TextView buy_ctzq_bottom_tv_title_bet;

	/** 投注协议布局 */
	View view_buy_ctzq_bet_protocol;
	CheckBox bet_protocol_choice;
	TextView bet_protocol;

	/** 投注数 */
	int betTotal;
	/** 倍数 */
	int a_multiple;

	/**
	 * 胜负彩场次数据
	 */
	private int issueID;
	private String issue;
	private String EndTime;
	private List<CtzqSfcMatche> matches;
	private MatchAdapter matchAdapter;
	private List<CtzqSfcMatche> matchesBet;
	private BetAdapter betAdapter;

	private PopupWindow m_popupWindow;

	private String paramsStr;

	private long endTime;// 结束时间
	Handler handler = new Handler();

	/** 判断是否从推送通知过来 */
	private Boolean ifPush;
	
	
	private View noDataView ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.buy_ctzq_rx9);
		ifPush = getIntent().getBooleanExtra("ifPush", false);
		initView();
		initData();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBack();
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DefConstants.REQ_CODE_BUYMAIN && resultCode == RESULT_OK) {
			this.finish();
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == DefConstants.REQ_CODE_NO_MONEY_2_RECHARGE) {
				finish();
			}
		}
	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		matches = new ArrayList<CtzqSfcMatche>();
		matchesBet = new ArrayList<CtzqSfcMatche>();
		matchAdapter = new MatchAdapter(this);
		buy_ctzq_rx9_list.setAdapter(matchAdapter);

		buy_ctzq_rx9_list_bet.addFooterView(view_buy_ctzq_bet_protocol);
		betAdapter = new BetAdapter(this);
		buy_ctzq_rx9_list_bet.setAdapter(betAdapter);

		String[] parms = new String[2];
		parms[0] = "204";
		JSONObject jsob = new JSONObject();
		try {
			jsob.put("LottID", LotConstants.LOT_ID_ZQ_RX9);
		} catch (JSONException ex) {
		}
		parms[1] = jsob.toString();

		AsyncLoader task = new AsyncLoader();
		task.execute(parms);

		// handler.postDelayed(runnable, 1000);
	}

	// 倒计时
	/*
	 * Runnable runnable = new Runnable() {
	 * 
	 * @Override public void run() { getCountDown(endTime--);
	 * handler.postDelayed(this, 1000); } }; private void getCountDown(long end)
	 * { if (end > 0) { String res = ""; long temp = 0; long d = end / 86400;
	 * temp = end - (d * 86400); if (d>0) { res += d + "天"; }
	 * 
	 * long h = temp / 3600; if (d>=0&&h>0) { res += h + "时"; } temp = temp - (h
	 * * 3600);
	 * 
	 * long m = temp / 60; if (d>=0&&h>=0&&m>0) { res += m + "分"; } temp = temp
	 * - (m * 60);
	 * 
	 * long s = temp; res += s + "秒";
	 * buy_ctzq_rx9_issue_and_endtime.setText(convertToHtml(issue, res)); } else
	 * { buy_ctzq_rx9_issue_and_endtime.setText(convertToHtml("--",
	 * "---------")); } }
	 */
	/**
	 * 初始化组件
	 */
	private void initView() {
		noDataView = findViewById(R.id.no_data);
		
		buy_ctzq_top_tv_left = (TextView) findViewById(R.id.buy_ctzq_top_tv_left);
		buy_ctzq_top_tv_right = (TextView) findViewById(R.id.buy_ctzq_top_tv_right);
		buy_ctzq_top_tv_title = (TextView) findViewById(R.id.buy_ctzq_top_tv_title);

		buy_ctzq_top_tv_left.setOnClickListener(btn_onclick);

		buy_ctzq_top_tv_title.setText("任选9");

		// buy_ctzq_top_tv_right.getBackground().setAlpha(255);
		buy_ctzq_top_tv_right.setVisibility(View.VISIBLE);

		buy_ctzq_top_tv_right.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater.from(CtzqRx9Activity.this);

				// 小目录框的设置
				View menuview = inflater.inflate(R.layout.public_menulink, null);
				m_popupWindow = new PopupWindow(menuview, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

				m_popupWindow.setBackgroundDrawable(new BitmapDrawable());
				m_popupWindow.setOutsideTouchable(true);
				m_popupWindow.showAtLocation(menuview, Gravity.RIGHT | Gravity.TOP, 0, 0);
				m_popupWindow.showAsDropDown(buy_ctzq_top_tv_right);

				menuview.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
					}
				});

				Button public_menulink_Button01 = (Button) menuview.findViewById(R.id.public_menulink_Button01);
				public_menulink_Button01.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent;
						m_popupWindow.dismiss();
						if (checkUserLogin()) {
							Intent intent0 = new Intent();
							intent0.putExtra("lotID", LotConstants.LOT_ID_ZQ_RX9);
							intent0.setClass(CtzqRx9Activity.this, BetRecordActivity.class);
							startActivity(intent0);
						} else {
							intent = new Intent(getApplicationContext(), LoginActivity.class);
							startActivityForResult(intent, DefConstants.REQ_CODE_ZQRX9);
						}
					}
				});

				Button public_menulink_Button02 = (Button) menuview.findViewById(R.id.public_menulink_Button02);
				public_menulink_Button02.setVisibility(View.GONE);
				// public_menulink_Button02.setOnClickListener(new
				// View.OnClickListener() {
				// @Override
				// public void onClick(View arg0) {
				// Intent intent;
				// m_popupWindow.dismiss();
				// if (checkUserLogin()) {
				// intent = new Intent(getApplicationContext(),
				// ZhRecordActivity.class);
				// startActivity(intent);
				// } else {
				// intent = new Intent(getApplicationContext(),
				// LoginActivity.class);
				// startActivityForResult(intent, DefConstants.REQ_CODE_ZQRX9);
				// }
				// }
				// });
				Button public_menulink_Button03 = (Button) menuview.findViewById(R.id.public_menulink_Button03);
				public_menulink_Button03.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
						Intent intent;
						intent = new Intent(getApplicationContext(), KjinfoListByType.class);
						intent.putExtra("LottID", "1");
						intent.putExtra("LottName", "胜负彩/任选9");
						startActivity(intent);
					}
				});
				Button public_menulink_Button04 = (Button) menuview.findViewById(R.id.public_menulink_Button04);
				public_menulink_Button04.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						m_popupWindow.dismiss();
						// Intent intent;
						// intent = new Intent(getApplicationContext(),
						// HelpActivity.class);
						// startActivity(intent);
						Intent intent = new Intent(getApplicationContext(), CaiPiaoHelp.class);
						intent.putExtra("cp_title", "任选九");
						intent.putExtra("cp_url", "rx9c.html");
						startActivity(intent);
					}
				});
			}
		});

		// 比赛布局
		view_buy_ctzq_rx9_matches = findViewById(R.id.view_buy_ctzq_rx9_matches);
		buy_ctzq_bottom_tv_left = (Button) findViewById(R.id.buy_ssqxh_Buttondel);
		buy_ctzq_bottom_tv_right = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_right);
		buy_ctzq_bottom_tv_title = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_title);

		buy_ctzq_bottom_tv_left.setOnClickListener(btn_onclick);
		buy_ctzq_bottom_tv_right.setOnClickListener(btn_onclick);

		buy_ctzq_rx9_list = (ListView) findViewById(R.id.buy_ctzq_rx9_list);
		buy_ctzq_rx9_issue_and_endtime = (TextView) findViewById(R.id.buy_ctzq_rx9_issue_and_endtime);

		// 投注布局
		view_buy_ctzq_rx9_bet = findViewById(R.id.view_buy_ctzq_rx9_bet);
		buy_ctzq_rx9_matches_and_endtime = (TextView) findViewById(R.id.buy_ctzq_rx9_matches_and_endtime);
		buy_ctzq_rx9_list_bet = (ListView) findViewById(R.id.buy_ctzq_rx9_list_bet);
		buy_ctzq_bottom_et_a_multiple = (EditText) findViewById(R.id.buy_ctzq_bottom_et_a_multiple);
		buy_ctzq_bottom_et_a_multiple.addTextChangedListener(textWatcher);
		buy_ctzq_bottom_tv_left_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_left_bet);
		buy_ctzq_bottom_tv_right_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_right_bet);
		buy_ctzq_bottom_tv_title_bet = (TextView) findViewById(R.id.buy_ctzq_bottom_tv_title_bet);

		buy_ctzq_bottom_tv_left_bet.setOnClickListener(btn_onclick);
		buy_ctzq_bottom_tv_right_bet.setOnClickListener(btn_onclick);

		buy_ctzq_rx9_add_match = findViewById(R.id.buy_ctzq_rx9_add_match);
		buy_ctzq_rx9_clear_match = findViewById(R.id.buy_ctzq_rx9_clear_match);
		buy_ctzq_rx9_add_match.setOnClickListener(btn_onclick);
		buy_ctzq_rx9_clear_match.setOnClickListener(btn_onclick);

		// 协议布局
		view_buy_ctzq_bet_protocol = LayoutInflater.from(this).inflate(R.layout.bet_protocol_foot, null);
		bet_protocol_choice = (CheckBox) view_buy_ctzq_bet_protocol.findViewById(R.id.bet_protocol_choice);
		bet_protocol = (TextView) view_buy_ctzq_bet_protocol.findViewById(R.id.bet_protocol);
		bet_protocol.setText(Html.fromHtml("<u>我已阅读并同意《代购合买协议》</u>"));

		bet_protocol_choice.setChecked(true);
		bet_protocol.setOnClickListener(btn_onclick);
	}

	private View.OnClickListener btn_onclick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.buy_ctzq_top_tv_left: // 返回
				onBack();
				break;
			case R.id.buy_ctzq_top_tv_right: // 功能
				break;
			case R.id.buy_ssqxh_Buttondel: // 清空
				onClear();
				/*MyDialog.Builder dialog = new MyDialog.Builder(CtzqRx9Activity.this);
				dialog.setTitle("清空场次提示");
				dialog.setMessage("清空后您已选择的场次列表将会清空，确认继续?");
				dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onClear();
						dialog.cancel();
					}
				});
				dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();*/

				break;
			case R.id.buy_ctzq_bottom_tv_right: // 确定
				int s = getBetCount() - 9;
				if (s >= 0) {
					showBetView();
				} else {
					showTip("您还需选择" + (-s) + "场比赛");
				}
				break;
			case R.id.buy_ctzq_bottom_tv_left_bet: // 合买
				if (betTotal > 0 && a_multiple > 0) {
					if (!bet_protocol_choice.isChecked()) {
						showTip("需要同意《代购合买协议》才可以继续购买");
						return;
					}
					if (checkUserLogin()) {
						runBetTask2();
					} else {
						Intent intent = new Intent(CtzqRx9Activity.this, LoginActivity.class);
						startActivityForResult(intent, DefConstants.REQ_CODE_ZQRX9);
					}
				} else {
					showTip("您的订单有误，请重新选定");
				}
				break;
			case R.id.buy_ctzq_bottom_tv_right_bet: // 投注
				if (betTotal > 0 && a_multiple > 0) {
					if (!bet_protocol_choice.isChecked()) {
						showTip("需要同意《代购合买协议》才可以继续购买");
						return;
					}
					if (checkUserLogin()) {
						// runBetTask();

						// 执行投注异步任务
						AsyncBetLoader task = new AsyncBetLoader();
						task.execute("207");
					} else {
						Intent intent = new Intent(CtzqRx9Activity.this, LoginActivity.class);
						startActivityForResult(intent, DefConstants.REQ_CODE_ZQRX9);
					}
				} else {
					showTip("您的订单有误，请重新选定");
				}
				break;
			case R.id.bet_protocol: // 协议
				startActivityForResult(new Intent(CtzqRx9Activity.this, BetProtocolActivity.class), 0);
				break;
			case R.id.buy_ctzq_rx9_add_match: // 添加比赛
				view_buy_ctzq_rx9_bet.setVisibility(View.GONE);
				view_buy_ctzq_rx9_matches.setVisibility(View.VISIBLE);
				matchAdapter.notifyDataSetChanged();
				break;
			case R.id.buy_ctzq_rx9_clear_match: // 清空选项
				matchesBet.clear();
				betAdapter.notifyDataSetChanged();
				showBetTotal();
				for (CtzqSfcMatche match : matches) {
					match.setBet_win(false);
					match.setBet_draw(false);
					match.setBet_lose(false);
					match.setBet_dan(false);
				}
				break;
			}
		}
	};

	/**
	 * 回退
	 */
	private void onBack() {
		if (view_buy_ctzq_rx9_bet.getVisibility() == View.VISIBLE) {

			MyDialog.Builder dialog = new MyDialog.Builder(this);
			dialog.setTitle("退出提示");
			dialog.setMessage("退出后您的投注将不会保存，确认继续?");
			dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					view_buy_ctzq_rx9_bet.setVisibility(View.GONE);
					buy_ctzq_top_tv_right.setVisibility(View.VISIBLE);
					view_buy_ctzq_rx9_matches.setVisibility(View.VISIBLE);
					onClear();
					// matchAdapter.notifyDataSetChanged();

					dialog.cancel();
				}
			});
			dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).create().show();

		} else {
			if(ifPush){
				Intent intent = new Intent(this, JddMainActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}

	protected void onClear() {
		// TODO Auto-generated method stub
		for (int i = 0; i < matches.size(); i++) {
			matches.get(i).setBet_win(false);
			matches.get(i).setBet_draw(false);
			matches.get(i).setBet_lose(false);
		}
		betChange();
	}

	/**
	 * 确认投注
	 */
	private void runBetTask() {
		MyDialog dialog = new MyDialog.Builder(this).setTitle("购买提示").setMessage("是否确认购买？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 执行投注异步任务
						AsyncBetLoader task = new AsyncBetLoader();
						task.execute("207");

						dialog.cancel();
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(true);// 设置back键是否可以取消
		dialog.show();
	}

	/**
	 * 确认合买
	 */
	private void runBetTask2() {
		Intent intent = new Intent();
		intent.putExtra("bs", a_multiple);
		intent.putExtra("AllMoney", betTotal * 2);
		intent.putExtra("IssueID", issueID + "");
		intent.putExtra("IssueName", issue);
		intent.putExtra("LotID", LotConstants.LOT_ID_ZQ_RX9);

		JSONObject params0 = new JSONObject();
		try {
			if (matchesBet.size() == 9) {
				params0.put("playid", 1902);
				intent.putExtra("PlayTypeId", 1902);
			} else if (matchesBet.size() > 9) {
				params0.put("playid", 1903);
				intent.putExtra("PlayTypeId", 1903);
			}
			params0.put("number", getBetNumber());
		} catch (JSONException e) {
			// e.printStackTrace();
		}
		intent.putExtra("Number", "[" + params0.toString() + "]");

		intent.setClass(this, FaQiHeMaiActivity.class);
		this.startActivityForResult(intent, DefConstants.REQ_CODE_BUYMAIN);
	}

	/**
	 * 格式化所选提示信息
	 * 
	 * @param selected
	 * @param total
	 * @return
	 */
	private Spanned convertToHtml(int selected) {
		return Html.fromHtml(String.format("已选<font color=red>%1$d</font>场比赛<br />至少选择9场比赛", selected));
	}

	private Spanned convertToHtml(String issue, String endtime) {
		return Html.fromHtml(String.format("第<font color=red>%1$s</font>期     投注截止：<font color=red>%2$s</font>", issue,
				endtime));
	}

	private Spanned convertToHtmlBet(int selected, String endtime) {
		return Html.fromHtml(String.format("共选择<font color=red>%1$d</font>场比赛     投注截止：%2$s", selected, endtime));
	}

	private Spanned convertToHtml(int score, String ossd) {
		String str = "";
		switch (score) {
		case 3:
			str = "胜";
			break;
		case 1:
			str = "平";
			break;
		case 0:
			str = "胜";
			break;
		}
		// return Html.fromHtml(String.format("<big>%1$d</big>　%2$s", score,
		// ossd));
		return Html.fromHtml(String.format("<big>%1$s</big>　%2$s", str, ossd));
	}

	/*
	 * private long setEndTime(String data){ Date nowTime = new
	 * Date(System.currentTimeMillis()); SimpleDateFormat sdf = new
	 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String retStrFormatNowDate =
	 * sdf.format(nowTime); long endTime = 0; try { long a =
	 * sdf.parse(retStrFormatNowDate).getTime(); long b =
	 * sdf.parse(data.toString()).getTime(); endTime = (b - a) / 1000; } catch
	 * (ParseException e) { // TODO Auto-generated catch block //
	 * e.printStackTrace(); } return endTime; }
	 */
	/**
	 * 任选9场次数据任务
	 */
	private class AsyncLoader extends AsyncTask<String, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			showdialog.showDialog(CtzqRx9Activity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;

			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params[1], UserID, action, getApplicationContext());
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (js.getInt("Code") == 0) {

						Map<String, Object> map = new HashMap<String, Object>();
						map = ConvertJsonToList.getMap(js.getString("Data"));

						issueID = Integer.parseInt(map.get("issueID").toString());
						issue = map.get("issue").toString();
						EndTime = map.get("EndTime").toString();
						// endTime = setEndTime(EndTime);
						buy_ctzq_rx9_issue_and_endtime.setText(convertToHtml(issue, EndTime));

						SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd HH:mm");

						List<Map<String, Object>> matchesList = ConvertJsonToList
								.getList(map.get("Matches").toString());
						for (int i = 0; i < matchesList.size(); i++) {
							CtzqSfcMatche match = new CtzqSfcMatche();
							match.setNo(matchesList.get(i).get("No").toString());
							match.setHTeam(matchesList.get(i).get("HTeam").toString());
							match.setVTeam(matchesList.get(i).get("VTeam").toString());
							try {
								match.setMatchTime(sdf2.format(sdf1.parse(matchesList.get(i).get("MatchTime")
										.toString())));
							} catch (ParseException e) {
								// e.printStackTrace();
							}
							String[] ouodds = matchesList.get(i).get("OuOdds").toString().split(" ");
							if (ouodds.length == 3) {
								match.setOuOdds_win(ouodds[0]);
								match.setOuOdds_draw(ouodds[1]);
								match.setOuOdds_lose(ouodds[2]);
							} else {
								match.setOuOdds_win("-");
								match.setOuOdds_draw("-");
								match.setOuOdds_lose("-");
							}
							match.setBet_win(false);
							match.setBet_draw(false);
							match.setBet_lose(false);
							match.setBet_dan(false);
							matches.add(match);
						}
						betChange();

					} else {
						
						buy_ctzq_rx9_issue_and_endtime.setVisibility(View.GONE);
						noDataView.setVisibility(View.VISIBLE);
						
						//String error = js.getString("Data");
						//showTip(error);
					}
				}
			} catch (JSONException e) {
				// e.printStackTrace();
			} finally {
				showdialog.closeDialog();
			}
		}

	}

	/**
	 * 任选9投注任务
	 */
	private class AsyncBetLoader extends AsyncTask<String, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			showdialog.showDialog(CtzqRx9Activity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;

			try {
				JSONObject param = new JSONObject();

				JSONObject params0 = new JSONObject();
				if (matchesBet.size() == 9) {
					params0.put("playid", 1902);
				} else if (matchesBet.size() > 9) {
					params0.put("playid", 1903);
				}
				params0.put("number", getBetNumber());

				param.put("SchemeType", 1); // 方案类型 1自购，2合买，3保存 1
				param.put("BetType", 1); // 投注类型 1选号投注 2单式上传 3先发后传 1
				param.put("BonusScale", 0); // 佣金比例
				param.put("AssureShare", 0); // 保底金额
				param.put("Description", ""); // 方案描述
				param.put("OpenUserList", ""); // 招股对象
				param.put("SecrecyLevel", 4); // 安全级别
				param.put("BuyShare", betTotal * a_multiple * 2); // 购买份数
																	// 自购等于方案金额
				param.put("Multiple", a_multiple); // 倍数
				param.put("LotteryID", LotConstants.LOT_ID_ZQ_RX9); // 彩种ID
				param.put("IssueID", issueID); //期次ID
				param.put("IssueName", issue);
				param.put("Number", "[" + params0.toString() + "]"); // 方案内容
				param.put("Money", betTotal * a_multiple * 2); // 方案金额
				paramsStr = param.toString();
				String UserID = ApplicationData.getInstance().getUserID();
				strResult = GetRequestParams.getRequestUserIDResult(param.toString(), UserID, action,
						getApplicationContext());
				return strResult;
			} catch (JSONException e) {
				// e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					int buy_icon;
					if (js.getInt("Code") != 0) {
						buy_icon = R.drawable.buy_failure;
						if(js.getString("Data").contains(Constants.BALANCE_BUZU)){
							Intent intent = new Intent();
							intent.setClass(CtzqRx9Activity.this, JddRechargeListActivity.class);
							intent.putExtra("params", paramsStr);
							startActivityForResult(intent, DefConstants.REQ_CODE_NO_MONEY_2_RECHARGE);
						} else {
							new ShowTipDialog().showBuyInfo(CtzqRx9Activity.this, js.getString("Data"), "购买失败", buy_icon,
									paramsStr);
						}
					} else {
						Map<String, Object> map = new HashMap<String, Object>();
						map = ConvertJsonToList.getMap(js.getString("Data"));

						buy_icon = R.drawable.buy_success;
						String msg = "发起任选9第" + issue + "期购买方案\n\n我的认购：" + (betTotal * a_multiple * 2)/* + "彩豆\n账户余额："
								+ map.get("Balance").toString()*/ + "彩豆"+"\n方案编号："+js.getString("Data").toString();
						new ShowTipDialog().showBuyInfo(CtzqRx9Activity.this, msg, "投注成功", buy_icon, paramsStr);

						// 存贮数据
						MyPreference.getInstance(CtzqRx9Activity.this).storeBLotID(LotConstants.LOT_ID_ZQ_RX9);

					}
				}
			} catch (JSONException e) {
				// e.printStackTrace();
			} finally {
				showdialog.closeDialog();
			}
		}

	}

	/**
	 * 自定义任选9数据适配器
	 */
	private class MatchAdapter extends BaseAdapter {

		private Context context;

		public MatchAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return matches.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return matches.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final CtzqSfcMatche match = matches.get(position);
			Holder holder = null;

			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.buy_ctzq_rx9_list_item, null);

				holder = new Holder();
				holder.buy_ctzq_rx9_list_item_no = (TextView) convertView.findViewById(R.id.buy_ctzq_rx9_list_item_no);
				holder.buy_ctzq_rx9_list_item_hteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_hteam);
				holder.buy_ctzq_rx9_list_item_vteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_vteam);
				holder.buy_ctzq_rx9_list_item_matchtime = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_matchtime);
				holder.buy_ctzq_rx9_list_item_bet_win = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_win);
				holder.buy_ctzq_rx9_list_item_bet_draw = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_draw);
				holder.buy_ctzq_rx9_list_item_bet_lose = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_lose);

				holder.buy_ctzq_rx9_list_item_hteam_vs_vteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_hteam_vs_vteam);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.buy_ctzq_rx9_list_item_no.setText(match.getNo());
			// holder.buy_ctzq_rx9_list_item_hteam.setText(match.getHTeam());
			// holder.buy_ctzq_rx9_list_item_vteam.setText(match.getVTeam());
			holder.buy_ctzq_rx9_list_item_matchtime.setText(match.getMatchTime());

			holder.buy_ctzq_rx9_list_item_bet_win.setSelected(match.isBet_win());
			if (match.isBet_win()) {
				holder.buy_ctzq_rx9_list_item_bet_win.setText(Html.fromHtml("<font size='18dip' color='#ffffff'>"
						+ match.getHTeam() + "</font><br>" + "胜"));
			} else {
				holder.buy_ctzq_rx9_list_item_bet_win.setText(Html.fromHtml("<font size='18dip' color='#fe5052'>"
						+ match.getHTeam() + "</font><br>" + "胜"));
			}
			// holder.buy_ctzq_rx9_list_item_bet_win.setText(convertToHtml(3,
			// match.getOuOdds_win()));
			holder.buy_ctzq_rx9_list_item_hteam.setText(match.getOuOdds_win());

			holder.buy_ctzq_rx9_list_item_bet_win.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_win(!match.isBet_win());
					betChange();
				}
			});

			// holder.buy_ctzq_rx9_list_item_bet_draw.setText(convertToHtml(1,
			// match.getOuOdds_draw()));
			holder.buy_ctzq_rx9_list_item_bet_draw.setSelected(match.isBet_draw());

			if (match.isBet_draw()) {
				holder.buy_ctzq_rx9_list_item_bet_draw.setText(Html
						.fromHtml("<font size='18dip' color='#ffffff'>VS</font><br>" + "平"));
			} else {
				holder.buy_ctzq_rx9_list_item_bet_draw.setText(Html
						.fromHtml("<font size='18dip' color='#fe5052'>VS</font><br>" + "平"));
			}
			holder.buy_ctzq_rx9_list_item_hteam_vs_vteam.setText(match.getOuOdds_draw());
			holder.buy_ctzq_rx9_list_item_bet_draw.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_draw(!match.isBet_draw());
					betChange();
				}
			});

			// holder.buy_ctzq_rx9_list_item_bet_lose.setText(convertToHtml(0,
			// match.getOuOdds_lose()));
			holder.buy_ctzq_rx9_list_item_bet_lose.setSelected(match.isBet_lose());

			if (match.isBet_lose()) {
				holder.buy_ctzq_rx9_list_item_bet_lose.setText(Html.fromHtml("<font size='18dip' color='#ffffff'>"
						+ match.getVTeam() + "</font><br>" + "胜"));
			} else {
				holder.buy_ctzq_rx9_list_item_bet_lose.setText(Html.fromHtml("<font size='18dip' color='#fe5052'>"
						+ match.getVTeam() + "</font><br>" + "胜"));
			}
			holder.buy_ctzq_rx9_list_item_vteam.setText(match.getOuOdds_lose());

			holder.buy_ctzq_rx9_list_item_bet_lose.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					match.setBet_lose(!match.isBet_lose());
					betChange();
				}
			});

			return convertView;
		}

		class Holder {
			TextView buy_ctzq_rx9_list_item_no;
			TextView buy_ctzq_rx9_list_item_hteam;
			TextView buy_ctzq_rx9_list_item_vteam;
			TextView buy_ctzq_rx9_list_item_hteam_vs_vteam;
			TextView buy_ctzq_rx9_list_item_matchtime;
			TextView buy_ctzq_rx9_list_item_bet_win;
			TextView buy_ctzq_rx9_list_item_bet_draw;
			TextView buy_ctzq_rx9_list_item_bet_lose;
		}

	}

	/**
	 * 自定义任选9投注适配器
	 */
	private class BetAdapter extends BaseAdapter {

		private Context context;

		public BetAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return matchesBet.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return matchesBet.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final CtzqSfcMatche match = matchesBet.get(position);
			Holder holder = null;

			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.buy_ctzq_rx9_list_item_bet, null);

				holder = new Holder();
				holder.buy_ctzq_rx9_list_item_no = (TextView) convertView.findViewById(R.id.buy_ctzq_rx9_list_item_no);
				holder.buy_ctzq_rx9_list_item_hteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_hteam);
				holder.buy_ctzq_rx9_list_item_vteam = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_vteam);
				holder.buy_ctzq_rx9_list_item_bet_win = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_win);
				holder.buy_ctzq_rx9_list_item_bet_draw = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_draw);
				holder.buy_ctzq_rx9_list_item_bet_lose = (TextView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_bet_lose);
				// holder.buy_ctzq_rx9_list_item_bet_dan = (TextView)
				// convertView.findViewById(R.id.buy_ctzq_rx9_list_item_bet_dan);
				holder.buy_ctzq_rx9_list_item_delete = (ImageView) convertView
						.findViewById(R.id.buy_ctzq_rx9_list_item_delete);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.buy_ctzq_rx9_list_item_no.setText(match.getNo());
			holder.buy_ctzq_rx9_list_item_hteam.setText(match.getHTeam());
			holder.buy_ctzq_rx9_list_item_vteam.setText(match.getVTeam());
			holder.buy_ctzq_rx9_list_item_bet_win.setSelected(match.isBet_win());
			holder.buy_ctzq_rx9_list_item_bet_draw.setSelected(match.isBet_draw());
			holder.buy_ctzq_rx9_list_item_bet_lose.setSelected(match.isBet_lose());
			// holder.buy_ctzq_rx9_list_item_bet_dan.setSelected(match.isBet_dan());
			// holder.buy_ctzq_rx9_list_item_bet_dan.setOnClickListener(new
			// View.OnClickListener() {
			// @Override
			// public void onClick(View v) {
			// for(int i=0; i<matches.size(); i++) {
			// if(matches.get(i).getNo().equals(match.getNo())) {
			// matches.get(i).setBet_dan(!matches.get(i).isBet_dan());
			// }
			// }
			// match.setBet_dan(!match.isBet_dan());
			// betAdapter.notifyDataSetChanged();
			// showBetTotal();
			// }
			// });

			// /********这里暂时不开放胆拖玩法********/
			// holder.buy_ctzq_rx9_list_item_bet_dan.setEnabled(false);
			// holder.buy_ctzq_rx9_list_item_bet_dan.setVisibility(View.GONE);
			// /************************************************/

			holder.buy_ctzq_rx9_list_item_delete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					for (int i = 0; i < matches.size(); i++) {
						if (matches.get(i).getNo().equals(match.getNo())) {
							matches.get(i).setBet_win(false);
							matches.get(i).setBet_draw(false);
							matches.get(i).setBet_lose(false);
							matches.get(i).setBet_dan(false);
						}
					}
					if (matches.size() < 9) {

						Toast.makeText(CtzqRx9Activity.this, "不能少于9场！", Toast.LENGTH_SHORT).show();
						;
					} else {
						matchesBet.remove(match);
						betAdapter.notifyDataSetChanged();
						showBetTotal();
					}

				}
			});
			holder.buy_ctzq_rx9_list_item_delete.setEnabled(matchesBet.size() > 9);

			return convertView;
		}

		class Holder {
			TextView buy_ctzq_rx9_list_item_no;
			TextView buy_ctzq_rx9_list_item_hteam;
			TextView buy_ctzq_rx9_list_item_vteam;
			TextView buy_ctzq_rx9_list_item_bet_win;
			TextView buy_ctzq_rx9_list_item_bet_draw;
			TextView buy_ctzq_rx9_list_item_bet_lose;
			// TextView buy_ctzq_rx9_list_item_bet_dan;
			ImageView buy_ctzq_rx9_list_item_delete;
		}

	}

	/**
	 * 获取投注内容
	 * 
	 * @return
	 */
	private String getBetNumber() {
		String number = "";

		for (int i = 0; i < matches.size(); i++) {
			String ball = "";
			if (matches.get(i).isBet_win())
				ball += "3";
			if (matches.get(i).isBet_draw())
				ball += "1";
			if (matches.get(i).isBet_lose())
				ball += "0";

			if (ball.equals(""))
				number += "#";
			else
				number += ball;

			number += ",";
		}

		number = number.substring(0, number.length() - 1);
		return number;
	}

	/**
	 * 获取当前已选择的比赛数目
	 */
	private int getBetCount() {
		int count = 0;

		for (int i = 0; i < matches.size(); i++) {
			CtzqSfcMatche match = matches.get(i);
			if (match.isBet_win() || match.isBet_draw() || match.isBet_lose()) {
				count++;
			}
		}

		return count;
	}

	/**
	 * 更新列表及选中信息
	 */
	private void betChange() {
		matchAdapter.notifyDataSetChanged();
		buy_ctzq_bottom_tv_title.setText(convertToHtml(getBetCount()));
	}

	/**
	 * 切换至投注界面
	 */
	protected void showBetView() {
		view_buy_ctzq_rx9_matches.setVisibility(View.GONE);
		view_buy_ctzq_rx9_bet.setVisibility(View.VISIBLE);

		buy_ctzq_top_tv_right.setVisibility(View.INVISIBLE);

		a_multiple = 1;
		buy_ctzq_bottom_et_a_multiple.setText("1");

		matchesBet.clear();
		for (int i = 0; i < matches.size(); i++) {
			CtzqSfcMatche match = matches.get(i);
			if (match.isBet_win() || match.isBet_draw() || match.isBet_lose()) {
				matchesBet.add(match);
			}
		}

		betAdapter.notifyDataSetChanged();
		showBetTotal();
	}

	private void showBetTotal() {
		buy_ctzq_rx9_matches_and_endtime.setText(convertToHtmlBet(getBetCount(), EndTime));
		betTotal = getBetTotal();
		buy_ctzq_bottom_tv_title_bet.setText("共" + betTotal * 2 * a_multiple + "彩豆");
	}

	/**
	 * 倍数输入变化
	 */
	TextWatcher textWatcher = new TextWatcher() {
		private boolean isChanged = false;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			/*
			 * if(s.toString().equals("")) { a_multiple = 0; } else { a_multiple
			 * = Integer.parseInt(s.toString()); }
			 * buy_ctzq_bottom_tv_title_bet.setText("共" + betTotal * 2 *
			 * a_multiple + "彩豆");
			 */
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (isChanged) {
				return;
			}
			isChanged = true;
			if (!buy_ctzq_bottom_et_a_multiple.getText().toString().equals("")) {

				int bs = Integer.parseInt(s.toString());
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (bs < 1) {
					Toast.makeText(CtzqRx9Activity.this, R.string.the_minimum_ratio_of_one, Toast.LENGTH_SHORT).show();
					buy_ctzq_bottom_et_a_multiple.setText("1");
					buy_ctzq_bottom_et_a_multiple.selectAll();
					a_multiple = 1;
				} else if (bs > 99999) {
					Toast.makeText(CtzqRx9Activity.this, R.string.the_maximum_ratio_of_nine_hundred_and_ninety_nine,
							Toast.LENGTH_SHORT).show();
					buy_ctzq_bottom_et_a_multiple.setText("99999");
					buy_ctzq_bottom_et_a_multiple.selectAll();
					a_multiple = 99999;
				} else {
					buy_ctzq_bottom_et_a_multiple.setText(str2);
					buy_ctzq_bottom_et_a_multiple.setSelection(buy_ctzq_bottom_et_a_multiple.length());
					a_multiple = Integer.parseInt(str2.toString());
				}

				// moneyText.setText(allMoney *
				// Integer.parseInt(buy_11x5xhlb_EditText01.getText().toString())
				// + "");
			} else {
				buy_ctzq_bottom_et_a_multiple.setText("1");
				buy_ctzq_bottom_et_a_multiple.selectAll();
				a_multiple = 1;
			}

			buy_ctzq_bottom_tv_title_bet.setText("共" + betTotal * 2 * a_multiple + "彩豆");
			isChanged = false;
			buy_ctzq_bottom_et_a_multiple.invalidate();

		}
	};

	/**
	 * 计算投注总数
	 * 
	 * @return
	 */
	private int getBetTotal() {
		int total;

		if (matchesBet.size() == 9) {
			total = 1;
			for (int i = 0; i < matchesBet.size(); i++) {
				int bet = getTeamCount(matchesBet.get(i));
				total *= bet;
			}

		} else if (matchesBet.size() > 9) {

			int a[] = new int[matchesBet.size()];
			for (int i = 0; i < matchesBet.size(); i++) {
				a[i] = i;
			}
			List<int[]> com = FactoryNum.combine1(a, 9);
			total = 0;
			for (int i = 0; i < com.size(); i++) {
				int[] mat = com.get(i);
				int mc = 1;
				mc = mc * getTeamCount(matchesBet.get(mat[0])) * getTeamCount(matchesBet.get(mat[1]))
						* getTeamCount(matchesBet.get(mat[2])) * getTeamCount(matchesBet.get(mat[3]))
						* getTeamCount(matchesBet.get(mat[4])) * getTeamCount(matchesBet.get(mat[5]))
						* getTeamCount(matchesBet.get(mat[6])) * getTeamCount(matchesBet.get(mat[7]))
						* getTeamCount(matchesBet.get(mat[8]));
				total += mc;
			}

		} else {

			total = 0;

		}

		return total;
	}

	/**
	 * 获取当前比赛投注种类（胜平负）数
	 * 
	 * @param match
	 * @return
	 */
	private int getTeamCount(CtzqSfcMatche match) {
		int bet = 0;
		if (match.isBet_win())
			bet++;
		if (match.isBet_draw())
			bet++;
		if (match.isBet_lose())
			bet++;
		return bet;
	}

	/** 显示文字提示 */
	private void showTip(String tip) {
		Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 登录检测
	 * 
	 * @return
	 */
	public boolean checkUserLogin() {
		if (!ApplicationData.getInstance().getLoginName().equals("")
				&& !ApplicationData.getInstance().getLoginPwd().equals("")
				|| !ApplicationData.getInstance().getUserID().equals("")) {
			return true;
		} else {
			return false;
		}
	}

}
